package org.example.managementsystem.controller;

import org.example.managementsystem.model.Schedule;
import org.example.managementsystem.repository.PersonDao;
import org.example.managementsystem.repository.ScheduleDao;
import org.example.managementsystem.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/schedules")
@CrossOrigin(origins = "*")
public class ScheduleController {

    @Autowired
    private ScheduleDao scheduleDao;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Autowired
    private PersonDao personDao;

    /**
     * 获取指定月份的所有排班信息
     */
    @GetMapping("/month/{year}/{month}")
    public ResponseEntity<List<Schedule>> getSchedulesByMonth(
            @PathVariable int year,
            @PathVariable int month) {
        List<Schedule> schedules = scheduleDao.findByYearAndMonth(year, month);
        return ResponseEntity.ok(schedules);
    }

    /**
     * 获取指定月份和部门的排班信息
     */
    @GetMapping("/month/{year}/{month}/department/{department}")
    public ResponseEntity<List<Schedule>> getSchedulesByMonthAndDepartment(
            @PathVariable int year,
            @PathVariable int month,
            @PathVariable String department) {
        List<Schedule> schedules = scheduleDao.findByYearAndMonthAndDepartment(year, month, department);
        return ResponseEntity.ok(schedules);
    }

    /**
     * 获取指定员工的排班信息
     */
    @GetMapping("/employee/{jobNumber}/{year}/{month}")
    public ResponseEntity<List<Schedule>> getEmployeeSchedules(
            @PathVariable String jobNumber,
            @PathVariable int year,
            @PathVariable int month) {
        List<Schedule> schedules = scheduleDao.findByYearAndMonth(year, month)
                .stream()
                .filter(s -> s.getJobNumber().equals(jobNumber) && s.getIsActive())
                .collect(Collectors.toList());
        return ResponseEntity.ok(schedules);
    }
    
    /**
     * 自动生成排班表
     */
    @PostMapping("/generate/{year}/{month}/{department}")
    public ResponseEntity<?> generateSchedules(
            @PathVariable int year,
            @PathVariable int month,
            @PathVariable String department,
            @RequestBody List<String> jobNumbers) {
        try {
            // 生成排班表
            List<Schedule> schedules = scheduleService.generateMonthlySchedule(year, month, department, jobNumbers);
            
            // 保存排班表
            scheduleService.saveSchedules(schedules);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "成功生成" + schedules.size() + "条排班记录");
            response.put("count", schedules.size());
            
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (IllegalArgumentException e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "生成排班失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取排班统计信息
     */
    @GetMapping("/statistics/{year}/{month}/{department}")
    public ResponseEntity<Map<String, Object>> getScheduleStatistics(
            @PathVariable int year,
            @PathVariable int month,
            @PathVariable String department) {
        Map<String, Object> statistics = scheduleService.getMonthlyStatistics(year, month, department);
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 创建新排班
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createSchedule(@RequestBody Schedule schedule) {
        Schedule savedSchedule = scheduleDao.save(schedule);
        Map<String, Object> response = new HashMap<>();
        response.put("id", savedSchedule.getId());
        response.put("message", "排班创建成功");
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    /**
     * 更新排班信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, String>> updateSchedule(
            @PathVariable Long id,
            @RequestBody Schedule schedule) {
        Map<String, String> response = new HashMap<>();
        if (!scheduleDao.existsById(id)) {
            response.put("message", "更新失败，未找到指定ID的排班");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        schedule.setId(id); // 确保ID一致
        scheduleDao.save(schedule);
        response.put("message", "排班信息更新成功");
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, String>> deleteSchedule(@PathVariable Long id) {
        Map<String, String> response = new HashMap<>();
        try {
            if (!scheduleDao.existsById(id)) {
                response.put("message", "删除失败，未找到指定ID的排班");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            scheduleDao.deleteById(id); // 可能触发外键约束异常
            response.put("message", "排班信息删除成功");
            return ResponseEntity.ok(response);
        } catch (DataIntegrityViolationException e) {
            response.put("message", "存在关联数据，无法直接删除排班");
            return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
        } catch (Exception e) {
            response.put("message", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 根据ID获取单个排班记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<Schedule> getScheduleById(@PathVariable Long id) {
        Schedule schedule = scheduleDao.findById(id);
        if (schedule != null) {
            return ResponseEntity.ok(schedule);
        }
        return ResponseEntity.notFound().build();
    }
}